#include "CodeAnalyzer.h"
#include <iostream>
#include <algorithm>
#include <cmath>

CodeAnalyzer::CodeAnalyzer() {
    reset();
}

void CodeAnalyzer::reset() {
    stats = CodeFeatureStats();
    detectedFeatures.clear();
    variableUsage.clear();
    expressionFrequency.clear();
    definedVariables.clear();
    usedVariables.clear();
}

void CodeAnalyzer::analyzeCode(ASTNode* root) {
    if (!root) return;

    reset();

    std::cerr << "Starting code analysis..." << std::endl;

    // 第一遍：收集基本统计信息
    analyzeNodeRecursively(root);

    // 第二遍：检测特征
    detectFeatures(root);

    // 第三遍：计算复杂度指标
    calculateComplexityMetrics(root);

    // 第四遍：检测死代码和未使用变量
    detectDeadCode(root);

    // 生成分析报告
    generateAnalysisReport();
}

void CodeAnalyzer::analyzeNodeRecursively(ASTNode* node, int depth) {
    if (!node) return;

    stats.totalNodes++;
    stats.maxNestingDepth = std::max(stats.maxNestingDepth, depth);

    // 分析表达式节点
    if (node->type == "AddExpr" || node->type == "MulExpr" ||
        node->type == "RelExpr" || node->type == "LAndExpr" ||
        node->type == "LOrExpr" || node->type == "UnaryExpr") {
        stats.expressionNodes++;
        analyzeExpression(node);
    }

    // 分析变量引用
    if (node->type == "VarRef") {
        stats.variableReferences++;
        usedVariables.insert(node->value);
        variableUsage[node->value]++;
    }

    // 分析函数调用
    if (node->type == "FuncCall") {
        stats.functionCalls++;
    }

    // 分析控制流
    if (node->type == "WhileStmt" || node->type == "ForStmt") {
        stats.loops++;
    }

    if (node->type == "IfStmt") {
        stats.conditionals++;
    }

    // 分析赋值语句
    if (node->type == "AssignStmt" || node->type == "DeclAssignStmt") {
        stats.assignments++;
    }

    // 分析变量定义
    if (node->type == "DeclAssignStmt") {
        for (const auto& child : node->children) {
            if (child->type == "ID") {
                definedVariables.insert(child->value);
                break;
            }
        }
    }

    // 递归分析子节点
    for (const auto& child : node->children) {
        analyzeNodeRecursively(child.get(), depth + 1);
    }
}

void CodeAnalyzer::analyzeExpression(ASTNode* node) {
    if (!node) return;

    // 检查是否是常量表达式
    if (isConstantExpression(node)) {
        stats.constantExpressions++;
    }

    // 生成表达式键并统计频率
    std::string exprKey = generateExpressionKey(node);
    expressionFrequency[exprKey]++;

    // 计算表达式复杂度
    int complexity = calculateExpressionComplexity(node);
    stats.averageExpressionComplexity =
        (stats.averageExpressionComplexity * (stats.expressionNodes - 1) + complexity) / stats.expressionNodes;
}

bool CodeAnalyzer::isConstantExpression(ASTNode* node) {
    if (!node) return false;

    if (node->type == "NumLiteral") return true;

    if (node->type == "AddExpr" || node->type == "MulExpr" ||
        node->type == "RelExpr" || node->type == "LAndExpr" ||
        node->type == "LOrExpr") {

        for (const auto& child : node->children) {
            if (!isConstantExpression(child.get())) {
                return false;
            }
        }
        return true;
    }

    return false;
}

std::string CodeAnalyzer::generateExpressionKey(ASTNode* node) {
    if (!node) return "";

    std::string key = node->type;
    if (!node->value.empty()) {
        key += ":" + node->value;
    }

    for (const auto& child : node->children) {
        key += "(" + generateExpressionKey(child.get()) + ")";
    }

    return key;
}

void CodeAnalyzer::detectFeatures(ASTNode* node) {
    if (!node) return;

    // 检测常量表达式
    if (stats.constantExpressions > 0) {
        detectedFeatures.insert(CodeFeature::CONSTANT_EXPRESSIONS);
    }

    // 检测公共子表达式
    for (const auto& pair : expressionFrequency) {
        if (pair.second > 1) {
            detectedFeatures.insert(CodeFeature::COMMON_SUBEXPRESSIONS);
            break;
        }
    }

    // 检测循环结构
    if (stats.loops > 0) {
        detectedFeatures.insert(CodeFeature::LOOPS);
    }

    // 检测条件语句
    if (stats.conditionals > 0) {
        detectedFeatures.insert(CodeFeature::CONDITIONALS);
    }

    // 检测函数调用
    if (stats.functionCalls > 0) {
        detectedFeatures.insert(CodeFeature::FUNCTION_CALLS);
    }

    // 检测嵌套结构
    if (stats.maxNestingDepth > 3) {
        detectedFeatures.insert(CodeFeature::NESTED_STRUCTURES);
    }

    // 检测复杂表达式
    if (stats.averageExpressionComplexity > 5) {
        detectedFeatures.insert(CodeFeature::COMPLEX_EXPRESSIONS);
    } else if (stats.expressionNodes > 0) {
        detectedFeatures.insert(CodeFeature::SIMPLE_EXPRESSIONS);
    }

    // 检测副作用
    if (hasSideEffects(node)) {
        detectedFeatures.insert(CodeFeature::SIDE_EFFECTS);
    }

    // 检测计算密集型特征
    if (stats.expressionNodes > stats.totalNodes * 0.3 ||
        stats.functionCalls > 5 ||
        stats.averageExpressionComplexity > 8) {
        detectedFeatures.insert(CodeFeature::COMPUTE_INTENSIVE);
    }

    // 检测内存密集型特征
    if (stats.variableReferences > stats.totalNodes * 0.4 ||
        stats.assignments > 10) {
        detectedFeatures.insert(CodeFeature::MEMORY_INTENSIVE);
    }

    // 检测矩阵操作
    if (stats.matrixOperations > 0) {
        detectedFeatures.insert(CodeFeature::MATRIX_OPERATIONS);
    }

    // 检测递归函数
    if (stats.recursiveCalls > 0) {
        detectedFeatures.insert(CodeFeature::RECURSIVE_FUNCTIONS);
    }

    // 递归检测子节点
    for (const auto& child : node->children) {
        detectFeatures(child.get());
    }
}

void CodeAnalyzer::detectDeadCode(ASTNode* node) {
    if (!node) return;

    // 检测未使用的变量
    for (const auto& var : definedVariables) {
        if (usedVariables.find(var) == usedVariables.end()) {
            stats.unusedVariables++;
        }
    }

    if (stats.unusedVariables > 0) {
        detectedFeatures.insert(CodeFeature::UNUSED_VARIABLES);
    }

    // 检测死代码语句
    if (node->type == "Expr") {
        if (!hasSideEffects(node)) {
            stats.deadCodeStatements++;
        }
    }

    if (stats.deadCodeStatements > 0) {
        detectedFeatures.insert(CodeFeature::DEAD_CODE);
    }

    // 递归检测子节点
    for (const auto& child : node->children) {
        detectDeadCode(child.get());
    }
}

bool CodeAnalyzer::hasSideEffects(ASTNode* node) {
    if (!node) return false;

    if (node->type == "FuncCall" || node->type == "AssignStmt") {
        return true;
    }

    for (const auto& child : node->children) {
        if (hasSideEffects(child.get())) {
            return true;
        }
    }

    return false;
}

void CodeAnalyzer::calculateComplexityMetrics(ASTNode* node) {
    if (!node) return;

    // 计算圈复杂度
    stats.cyclomaticComplexity = calculateCyclomaticComplexity(node);

    // 计算代码密度
    stats.codeDensity = calculateCodeDensity(node);
}

int CodeAnalyzer::calculateExpressionComplexity(ASTNode* node) {
    if (!node) return 0;

    int complexity = 1;

    if (node->type == "AddExpr" || node->type == "MulExpr") {
        complexity += 2;
    } else if (node->type == "RelExpr" || node->type == "LAndExpr" || node->type == "LOrExpr") {
        complexity += 3;
    } else if (node->type == "FuncCall") {
        complexity += 5;
    }

    for (const auto& child : node->children) {
        complexity += calculateExpressionComplexity(child.get());
    }

    return complexity;
}

int CodeAnalyzer::calculateCyclomaticComplexity(ASTNode* node) {
    if (!node) return 1;

    int complexity = 1;

    if (node->type == "IfStmt" || node->type == "WhileStmt" ||
        node->type == "ForStmt" || node->type == "LAndExpr" ||
        node->type == "LOrExpr") {
        complexity++;
    }

    for (const auto& child : node->children) {
        complexity += calculateCyclomaticComplexity(child.get()) - 1;
    }

    return complexity;
}

double CodeAnalyzer::calculateCodeDensity(ASTNode* node) {
    if (!node) return 0.0;

    int meaningfulNodes = 0;
    int totalNodes = 0;

    calculateDensityRecursive(node, meaningfulNodes, totalNodes);

    return totalNodes > 0 ? static_cast<double>(meaningfulNodes) / totalNodes : 0.0;
}

void CodeAnalyzer::calculateDensityRecursive(ASTNode* node, int& meaningfulNodes, int& totalNodes) {
    if (!node) return;

    totalNodes++;

    if (node->type == "AddExpr" || node->type == "MulExpr" ||
        node->type == "AssignStmt" || node->type == "FuncCall" ||
        node->type == "IfStmt" || node->type == "WhileStmt") {
        meaningfulNodes++;
    }

    for (const auto& child : node->children) {
        calculateDensityRecursive(child.get(), meaningfulNodes, totalNodes);
    }
}

ComplexityLevel CodeAnalyzer::getComplexityLevel() const {
    if (stats.cyclomaticComplexity <= 2 && stats.maxNestingDepth <= 2 &&
        stats.averageExpressionComplexity <= 3) {
        return ComplexityLevel::VERY_SIMPLE;
    } else if (stats.cyclomaticComplexity <= 5 && stats.maxNestingDepth <= 3 &&
               stats.averageExpressionComplexity <= 5) {
        return ComplexityLevel::SIMPLE;
    } else if (stats.cyclomaticComplexity <= 10 && stats.maxNestingDepth <= 4 &&
               stats.averageExpressionComplexity <= 8) {
        return ComplexityLevel::MODERATE;
    } else if (stats.cyclomaticComplexity <= 20 && stats.maxNestingDepth <= 6 &&
               stats.averageExpressionComplexity <= 12) {
        return ComplexityLevel::COMPLEX;
    } else {
        return ComplexityLevel::VERY_COMPLEX;
    }
}

OptimizationStrategy CodeAnalyzer::suggestOptimizationStrategy() {
    OptimizationStrategy strategy;
    strategy.complexityLevel = getComplexityLevel();

    // 根据复杂度级别和建议优化级别
    strategy.suggestedOptimizationLevel = suggestOptimizationLevel();

    // 根据检测到的特征推荐优化
    if (detectedFeatures.find(CodeFeature::CONSTANT_EXPRESSIONS) != detectedFeatures.end()) {
        strategy.recommendedOptimizations.push_back(OptimizationType::CONSTANT_FOLDING);
    }

    if (detectedFeatures.find(CodeFeature::COMMON_SUBEXPRESSIONS) != detectedFeatures.end()) {
        strategy.recommendedOptimizations.push_back(OptimizationType::COMMON_SUBEXPRESSION_ELIMINATION);
    }

    if (detectedFeatures.find(CodeFeature::UNUSED_VARIABLES) != detectedFeatures.end() ||
        detectedFeatures.find(CodeFeature::DEAD_CODE) != detectedFeatures.end()) {
        strategy.recommendedOptimizations.push_back(OptimizationType::DEAD_CODE_ELIMINATION);
    }

    // 可选优化
    if (detectedFeatures.find(CodeFeature::COMPLEX_EXPRESSIONS) != detectedFeatures.end()) {
        strategy.optionalOptimizations.push_back(OptimizationType::ALGEBRAIC_OPTIMIZATION);
    }

    if (detectedFeatures.find(CodeFeature::LOOPS) != detectedFeatures.end()) {
        strategy.optionalOptimizations.push_back(OptimizationType::LOOP_OPTIMIZATION);
    }

    // 激进优化
    if (strategy.complexityLevel == ComplexityLevel::VERY_COMPLEX) {
        strategy.aggressiveOptimizations.push_back(OptimizationType::REGISTER_ALLOCATION);
        strategy.aggressiveOptimizations.push_back(OptimizationType::INLINING);
    }

    // 向量化优化（针对有循环的复杂代码）
    if (detectedFeatures.find(CodeFeature::LOOPS) != detectedFeatures.end() &&
        detectedFeatures.find(CodeFeature::COMPUTE_INTENSIVE) != detectedFeatures.end()) {
        strategy.aggressiveOptimizations.push_back(OptimizationType::VECTORIZATION);
    }

    // 生成推理说明
    strategy.reasoning = generateReasoning();

    return strategy;
}

int CodeAnalyzer::suggestOptimizationLevel() {
    ComplexityLevel level = getComplexityLevel();

    switch (level) {
        case ComplexityLevel::VERY_SIMPLE:
            return 0; // 无优化
        case ComplexityLevel::SIMPLE:
            return 1; // 基本优化
        case ComplexityLevel::MODERATE:
            return 2; // 标准优化
        case ComplexityLevel::COMPLEX:
            return 2; // 标准优化
        case ComplexityLevel::VERY_COMPLEX:
            return 3; // 激进优化
        default:
            return 2;
    }
}

std::vector<OptimizationType> CodeAnalyzer::getRecommendedOptimizations() {
    OptimizationStrategy strategy = suggestOptimizationStrategy();
    std::vector<OptimizationType> optimizations;

    optimizations.insert(optimizations.end(),
                        strategy.recommendedOptimizations.begin(),
                        strategy.recommendedOptimizations.end());

    return optimizations;
}

std::string CodeAnalyzer::generateReasoning() {
    std::string reasoning = "Code analysis results: ";

    reasoning += "Complexity level: " + std::to_string(static_cast<int>(getComplexityLevel())) + ", ";
    reasoning += "Cyclomatic complexity: " + std::to_string(stats.cyclomaticComplexity) + ", ";
    reasoning += "Max nesting depth: " + std::to_string(stats.maxNestingDepth) + ", ";
    reasoning += "Expression complexity: " + std::to_string(stats.averageExpressionComplexity) + ". ";

    reasoning += "Detected features: ";
    for (const auto& feature : detectedFeatures) {
        reasoning += std::to_string(static_cast<int>(feature)) + " ";
    }

    return reasoning;
}

void CodeAnalyzer::generateAnalysisReport() {
    std::cerr << "\n=== Code Analysis Report ===" << std::endl;
    printFeatureSummary();
    printComplexityAnalysis();

    OptimizationStrategy strategy = suggestOptimizationStrategy();
    std::cerr << "\n--- Optimization Strategy ---" << std::endl;
    std::cerr << "Suggested optimization level: " << strategy.suggestedOptimizationLevel << std::endl;
    std::cerr << "Reasoning: " << strategy.reasoning << std::endl;

    if (!strategy.recommendedOptimizations.empty()) {
        std::cerr << "Recommended optimizations: ";
        for (auto opt : strategy.recommendedOptimizations) {
            std::cerr << static_cast<int>(opt) << " ";
        }
        std::cerr << std::endl;
    }
}

void CodeAnalyzer::printFeatureSummary() const {
    std::cerr << "Total nodes: " << stats.totalNodes << std::endl;
    std::cerr << "Expression nodes: " << stats.expressionNodes << std::endl;
    std::cerr << "Constant expressions: " << stats.constantExpressions << std::endl;
    std::cerr << "Variable references: " << stats.variableReferences << std::endl;
    std::cerr << "Function calls: " << stats.functionCalls << std::endl;
    std::cerr << "Loops: " << stats.loops << std::endl;
    std::cerr << "Conditionals: " << stats.conditionals << std::endl;
    std::cerr << "Assignments: " << stats.assignments << std::endl;
    std::cerr << "Unused variables: " << stats.unusedVariables << std::endl;
    std::cerr << "Dead code statements: " << stats.deadCodeStatements << std::endl;
}

void CodeAnalyzer::printComplexityAnalysis() const {
    std::cerr << "\n--- Complexity Analysis ---" << std::endl;
    std::cerr << "Average expression complexity: " << stats.averageExpressionComplexity << std::endl;
    std::cerr << "Max nesting depth: " << stats.maxNestingDepth << std::endl;
    std::cerr << "Cyclomatic complexity: " << stats.cyclomaticComplexity << std::endl;
    std::cerr << "Code density: " << stats.codeDensity << std::endl;
    std::cerr << "Complexity level: " << static_cast<int>(getComplexityLevel()) << std::endl;
}

CodeFeatureStats CodeAnalyzer::getStats() const {
    return stats;
}

std::set<CodeFeature> CodeAnalyzer::getDetectedFeatures() const {
    return detectedFeatures;
}
